<template>
  <div class="custom-image-preview">
    <!-- 空状态提示 -->
    <div v-if="imageList.length === 0" class="empty-tip">
      <i class="empty-icon">📷</i>
      <p>暂无图片可预览</p>
    </div>

    <!-- 缩略图列表 -->
    <div v-else class="image-list">
      <img
        v-for="(src, index) in imageList"
        :key="index"
        :src="src"
        class="preview-thumb"
        @click="handleThumbClick(index)"
        :alt="`预览图片 ${index + 1}`"
        @error="handleImageError(index)"
      >
    </div>

    <!-- 预览模态框 -->
    <div
      v-if="isShow && imageList.length > 0"
      class="preview-modal"
      @click="handleModalClick"
    >
      <!-- 关闭按钮 -->
      <button class="close-btn" @click.stop="handleClose">×</button>

      <!-- 上一张/下一张按钮 -->
      <button
        v-if="false"
        class="prev-btn"
        @click.stop="prevImage"
        :disabled="currentIndex <= 0"
      >
        ←
      </button>
      <button
        v-if="false"
        class="next-btn"
        @click.stop="nextImage"
        :disabled="currentIndex >= imageList.length - 1"
      >
        →
      </button>

      <!-- 图片容器 -->
      <div class="image-container">
        <!-- 图片加载失败提示 -->
        <div v-if="currentImageError" class="image-error">
          <i>❌</i>
          <p>图片加载失败</p>
        </div>

        <!-- 预览图片 -->
        <img
          v-else
          :src="currentImage"
          :alt="`当前预览图片 ${currentIndex + 1}`"
          class="preview-img"
          @mousewheel="handleZoom"
          ref="previewImg"
          @error="currentImageError = true"
          @mousedown="startDrag"
        >
      </div>

      <!-- 图片信息和缩放控制 -->
      <div class="image-info">
        <span>{{ currentIndex + 1 }} / {{ imageList.length }}</span>
        <div class="zoom-controls">
          <button @click.stop="zoom(0.1)">+</button>
          <button @click.stop="zoom(-0.1)">-</button>
          <button @click.stop="resetZoom">↻ </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CustomImagePreview',
  props: {
    /**
     * 控制预览框显示/隐藏
     * 由父组件通过 .sync 双向绑定控制
     */
    isShow: {
      type: Boolean,
      default: false
    },
    /**
     * 图片URL列表
     */
    imageList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      currentIndex: 0, // 当前显示的图片索引
      scale: 1, // 缩放比例
      isDragging: false, // 是否正在拖拽图片
      startX: 0, // 拖拽起始X坐标
      startY: 0, // 拖拽起始Y坐标
      offsetX: 0, // X轴偏移量
      offsetY: 0, // Y轴偏移量
      currentImageError: false, // 当前图片是否加载失败
      errorImages: [] // 记录所有加载失败的图片索引
    };
  },
  computed: {
    /**
     * 获取当前显示的图片URL
     */
    currentImage() {
      if (this.imageList.length > 0 && this.currentIndex < this.imageList.length) {
        return this.imageList[this.currentIndex];
      }
      return '';
    }
  },
  watch: {
    /**
     * 监听isShow变化，当从父组件打开预览时重置状态
     */
    isShow(newVal) {
      if (newVal && this.imageList.length > 0) {
        this.resetZoom();
        this.currentImageError = this.errorImages.includes(this.currentIndex);
      }
    }
  },
  methods: {
    /**
     * 点击缩略图打开预览
     * @param {number} index - 图片索引
     */
    handleThumbClick(index) {
      if (this.imageList.length === 0) return;
      this.currentIndex = index;
      this.$emit('update:isShow', true); // 通知父组件打开预览
    },

    /**
     * 关闭预览
     */
    handleClose() {
      this.$emit('update:isShow', false); // 通知父组件关闭预览
    },

    /**
     * 切换到上一张图片
     */
    prevImage() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
        this.currentImageError = this.errorImages.includes(this.currentIndex);
        this.resetZoom();
      }
    },

    /**
     * 切换到下一张图片
     */
    nextImage() {
      if (this.currentIndex < this.imageList.length - 1) {
        this.currentIndex++;
        this.currentImageError = this.errorImages.includes(this.currentIndex);
        this.resetZoom();
      }
    },

    /**
     * 缩放图片
     * @param {number} delta - 缩放增量（正数放大，负数缩小）
     */
    zoom(delta) {
      // 限制缩放范围：0.1-5倍
      this.scale = Math.max(0.1, Math.min(this.scale + delta, 5));
      this.updateImageTransform();
    },

    /**
     * 重置图片缩放和位置
     */
    resetZoom() {
      this.scale = 1;
      this.offsetX = 0;
      this.offsetY = 0;
      this.updateImageTransform();
    },

    /**
     * 处理鼠标滚轮缩放
     * @param {Event} e - 鼠标事件
     */
    handleZoom(e) {
      e.preventDefault();
      const delta = e.deltaY < 0 ? 0.1 : -0.1;
      this.zoom(delta);
    },

    /**
     * 更新图片变换（缩放+位移）
     */
    updateImageTransform() {
      const img = this.$refs.previewImg;
      if (img) {
        img.style.transform = `scale(${this.scale}) translate(${this.offsetX}px, ${this.offsetY}px)`;
      }
    },

    /**
     * 开始拖拽图片
     * @param {Event} e - 鼠标事件
     */
    startDrag(e) {
      this.isDragging = true;
      this.startX = e.clientX - this.offsetX;
      this.startY = e.clientY - this.offsetY;

      // 绑定鼠标移动和释放事件
      window.addEventListener('mousemove', this.handleDrag);
      window.addEventListener('mouseup', this.stopDrag);
    },

    /**
     * 处理拖拽移动
     * @param {Event} e - 鼠标事件
     */
    handleDrag(e) {
      if (this.isDragging) {
        this.offsetX = e.clientX - this.startX;
        this.offsetY = e.clientY - this.startY;
        this.updateImageTransform();
      }
    },

    /**
     * 停止拖拽
     */
    stopDrag() {
      this.isDragging = false;
      window.removeEventListener('mousemove', this.handleDrag);
      window.removeEventListener('mouseup', this.stopDrag);
    },

    /**
     * 点击模态框空白处关闭预览
     * @param {Event} e - 点击事件
     */
    handleModalClick(e) {
      if (e.target === e.currentTarget) {
        this.handleClose();
      }
    },

    /**
     * 处理图片加载失败
     * @param {number} index - 失败图片的索引
     */
    handleImageError(index) {
      if (!this.errorImages.includes(index)) {
        this.errorImages.push(index);
      }
    },

    /**
     * 处理键盘事件（左右箭头切换，ESC关闭）
     * @param {Event} e - 键盘事件
     */
    handleKeydown(e) {
      if (!this.isShow || this.imageList.length === 0) return;

      if (e.key === 'ArrowLeft') {
        this.prevImage();
      } else if (e.key === 'ArrowRight') {
        this.nextImage();
      } else if (e.key === 'Escape') {
        this.handleClose();
      }
    }
  },
  mounted() {
    // 监听键盘事件
    window.addEventListener('keydown', this.handleKeydown);
  },
  beforeDestroy() {
    // 移除事件监听，防止内存泄漏
    window.removeEventListener('keydown', this.handleKeydown);
    window.removeEventListener('mousemove', this.handleDrag);
    window.removeEventListener('mouseup', this.stopDrag);
  }
};
</script>

<style scoped>
/* 空状态提示样式 */
.empty-tip {
  padding: 50px 20px;
  text-align: center;
  color: #999;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin: 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 15px;
  display: inline-block;
}

/* 缩略图列表样式 */
.image-list {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  padding: 20px;
}

.preview-thumb {
  width: 150px;
  height: 100px;
  object-fit: cover;
  cursor: pointer;
  border-radius: 4px;
  transition: transform 0.2s;
  border: 1px solid #eee;
}

.preview-thumb:hover {
  transform: scale(1.05);
}

/* 预览模态框样式 */
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 关闭按钮样式 */
.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  font-size: 20px;
  cursor: pointer;
  transition: background 0.2s;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.8);
}

/* 上下张按钮样式 */
.prev-btn, .next-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 50px;
  height: 50px;
  font-size: 20px;
  cursor: pointer;
  transition: background 0.2s;
  z-index: 10;
}

.prev-btn {
  left: 20px;
}

.next-btn {
  right: 20px;
}

.prev-btn:hover, .next-btn:hover {
  background: rgba(0, 0, 0, 0.8);
}

.prev-btn:disabled, .next-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 图片容器样式 */
.image-container {
  width: 90%;
  height: 80%;
  display: flex;
  align-items: center;
  justify-content: right;
  overflow: hidden;
  position: relative;
}

.preview-img {
  max-width: 100%;
  max-height: 100%;
  transition: transform 0.2s ease;
  cursor: move;
}

/* 图片加载失败样式 */
.image-error {
  color: white;
  text-align: center;
  padding: 20px;
}

.image-error i {
  font-size: 48px;
  margin-bottom: 15px;
  display: inline-block;
}

/* 图片信息和缩放控制样式 */
.image-info {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  color: white;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  align-items: center;
}

.zoom-controls {
  display: flex;
  gap: 10px;
}

.zoom-controls button {
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 30px;
  height: 30px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}

.zoom-controls button:hover {
  background: rgba(0, 0, 0, 0.8);
}
</style>
